package epfc.tfe.ts.web.customers;

import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import epfc.tfe.ts.domain.Customer;
import epfc.tfe.ts.service.customer.CustomerManager;

@Controller
@RequestMapping("/customers")
public class CustomerController {

	public static final String CUSTOMER_LIST = "customers/customerlist";
	public static final String VIEW_CUSTOMER = "customers/viewcustomer";
	public static final String EDIT_CUSTOMER = "customers/editcustomer";
	
	private final CustomerManager customerManager;
	
	@Autowired
	public CustomerController(CustomerManager customerManager){
		this.customerManager = customerManager;
	}
	
	@RequestMapping(value="/customerlist", method = RequestMethod.GET)
	@ModelAttribute("list") 
	// the return of the method is put in the "list" attribute
	// it is to be accessed through ${list} in the jsp (not model.list)
	public Collection<Customer> getCustomerList(){
		return customerManager.getCustomers();
	}
	
	@RequestMapping(value="/newcustomer", method = RequestMethod.GET)
	public Customer newCustomer(){
		return new Customer();
	}
	
	@RequestMapping(value="/create", method = RequestMethod.POST)
	public String addCustomer(@ModelAttribute Customer customer){
		this.customerManager.create(customer);
		return "redirect:/ts/" + CustomerController.CUSTOMER_LIST;
	}
	
	//this is problematic, it tries to match a jsp in .../viewcustomer/3.jsp form if not providing an explicit view
	@RequestMapping(value="/viewcustomer/{id}", method = RequestMethod.GET)
	public String viewCustomer(@PathVariable Long id, Model model){
		model.addAttribute("customer", this.customerManager.read(id));
		return VIEW_CUSTOMER;
	}
	
	@RequestMapping(value="/editcustomer/{id}", method = RequestMethod.GET)
	public String editCustomer(@PathVariable Long id, Model model){
		model.addAttribute("customer", this.customerManager.read(id));
		return EDIT_CUSTOMER;
	}
	
	@RequestMapping(value="/update", method = RequestMethod.POST)
	public String update(@ModelAttribute Customer customer){
		this.customerManager.update(customer);
		return "redirect:/ts/" + VIEW_CUSTOMER + "/" + customer.getId();
	}
	
	
}
